package com.yao.mall.interceptor;

import cn.hutool.json.JSONUtil;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.common.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiahua.yao
 * @version 1.0
 * @description 配合刷新登录时间的拦截器实现半小时内保持登录态
 * @date 2024/3/1 14:25
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //ThreadLocal中是否有用户
        if(UserHolder.getUser() == null){
            // 设置响应内容类型为application/json
            response.setContentType("application/json;charset=UTF-8");
            // 构建拦截通知信息
            Map<String, String> notification = new HashMap<>();
            notification.put("status", "401");
            notification.put("message", "您的请求被拦截，请检查是否登录。");
            // 将通知对象转换为JSON字符串
            String jsonNotification = JSONUtil.toJsonStr(notification);
            // 向客户端发送JSON格式的通知
            response.getWriter().write(jsonNotification);
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
